#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <functional>

#include "sock.hpp"

namespace Server
{
    using func_t = std::function<std::string(const std::string &)>;
    const uint16_t defaultPort = 8080;
    const int fdnum = sizeof(fd_set) * 8;
    const int defaultnum = -1;
    class SelectServer
    {
    public:
        SelectServer(func_t f, int port)
            : _func(f), _listensock(-1), _port(port)
        {
        }

        ~SelectServer()
        {
            if (_listensock)
            {
                close(_listensock);
            }

            if (_fdarray)
            {
                delete[] _fdarray;
            }
        }

        void InitServer()
        {
            _listensock = Sock::Socket();
            Sock::Bind(_listensock, _port);
            Sock::Listen(_listensock);
            _fdarray = new int[fdnum];
            for (int i = 0; i < fdnum; i++)
            {
                _fdarray[i] = defaultnum;
            }
            _fdarray[0] = _listensock;
        }

        void Print()
        {
            std::cout << "fd list: ";
            for (int i = 0; i < fdnum; i++)
            {
                if (_fdarray[i] != defaultnum)
                {
                    std::cout << _fdarray[i] << " ";
                }
            }
            std::cout << std::endl;
        }

        void Accpeter(int listensock)
        {
            // 获取新连接后，直接添加进入到 _fdarray 数组中
            logMessage(NORMAL, "Accpeter begin ...\n");
            uint16_t clientPort = 0;
            std::string clientIP;
            int sock = Sock::Accpet(listensock, &clientPort, &clientIP);
            if (sock < 0)
            {
                return;
            }
            int i = 0;
            for (; i < fdnum; i++)
            {
                if (_fdarray[i] != defaultnum)
                {
                    continue;
                }
                else
                {
                    break;
                }
            }

            // 找到位置
            if (i == fdnum)
            {
                // 说明已经满了
                logMessage(WARNING, "server is full,please wait ...\n");
            }
            else
            {
                _fdarray[i] = sock;
            }

            // 进行打印
            Print();
            logMessage(NORMAL, "Accpeter end ...\n");
        }

        void Recver(int sock, int i)
        {
            // 通过sock这个fd进行接受数据
            logMessage(NORMAL, "Recver begin ...\n");
            char buffer[1024];
            ssize_t n = recv(sock, buffer, sizeof(buffer) - 1, 0); // 这里读取不会阻塞，只有sock就绪了，才进来
            if (n > 0)
            {
                buffer[n - 1] = 0;
                logMessage(NORMAL, "client# %s", buffer);
            }
            else if (n < 0)
            {
                // 读取错误
                close(sock);
                _fdarray[i] = defaultnum;
                logMessage(WARNING, "recv error# %s", strerror(errno));
                return;
            }
            else // == 0
            {
                // client 退出了
                close(sock);
                _fdarray[i] = defaultnum;
                logMessage(NORMAL, "client quit,me too ...");
                return;
            }

            // 此时数据都在buffer当中，处理 request
            std::string response = _func(buffer);

            write(sock, response.c_str(), response.size());
            logMessage(NORMAL, "Recver end ...\n");
        }

        // 处理逻辑
        void Handerevent(fd_set &rfd)
        {
            // 判断是listensock，还是普通sock的
            for (int i = 0; i < fdnum; i++)
            {
                if (_fdarray[i] == defaultnum)
                {
                    continue; // 后面需要进行置空，不能break
                }
                if (_fdarray[i] == _listensock && FD_ISSET(_fdarray[i], &rfd))
                {
                    // 需要进行accpet
                    Accpeter(_fdarray[i]);
                }
                else if (FD_ISSET(_fdarray[i], &rfd))
                {
                    // 其他fd 而且就绪
                    Recver(_fdarray[i], i);
                }
                else
                {
                }
            }
        }

        void Start()
        {
            // 等 + 处理数据  select返回的是fd的个数
            for (;;)
            {
                fd_set rfd;
                // 初始化rfd
                FD_ZERO(&rfd);
                int maxfd = _fdarray[0]; // 最大fd数 +1

                for (int i = 0; i < fdnum; i++)
                {
                    if (_fdarray[i] == defaultnum)
                    {
                        continue;
                    }
                    // 将这个fd 设置进入rfd中
                    FD_SET(_fdarray[i], &rfd);
                    if (_fdarray[i] > maxfd)
                    {
                        maxfd = _fdarray[i];
                    }
                }

                logMessage(NORMAL, "max fd is: %d\n", maxfd);
                // 非阻塞 每隔一秒，询问一下
                //struct timeval _timeval = {1, 0};
                // int n = select(maxfd + 1, &rfd, nullptr, nullptr, &_timeval);
                struct timeval _timeval = {5, 0};
                int n = select(maxfd + 1, &rfd, nullptr, nullptr, &_timeval);
                switch (n)
                {
                case 0:
                    // 超时
                    logMessage(NORMAL, "time out ...");
                    break;
                case -1:
                    logMessage(WARNING, "select errno code: %d, select errno message: %s", errno, strerror(errno));
                    break;
                default:
                    // 走到这里说明有fd就绪了，需要进行处理，但是只有 listensock 就绪
                    logMessage(NORMAL, "have event ready!\n");
                    // 进行业务逻辑处理
                    Handerevent(rfd);
                    break;
                }
            }
        }

    private:
        int _port;
        int _listensock;
        int *_fdarray; // 维护的accpet的fd数组
        func_t _func;
    };
}